package com.yotoodesign.dianba.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.widget.Toast;

/**
 * HTTP下载类
 * 
 * @author wanglin
 */

public class HttpDownloader {
	private URL url = null;
	/*
	 * 该函数返回整型: -1:代表出错 , 0:代表成功 , 1:代表已经存在
	 * 
	 * @description 下载的通用方法
	 * 
	 * @param urlStr
	 * 
	 * @param path
	 * 
	 * @param fileName
	 * 
	 * @return
	 */
	public int downFile(Context context, String urlStr, String path,
	String fileName) {
		InputStream inputStream = null;
		FileUtils fileUtils = new FileUtils();
		if (fileUtils.isFileExist(path + fileName)) {
			Toast.makeText(context, "文件已经存在", Toast.LENGTH_LONG).show();
			return 1;
		} else {
			try {
				inputStream = getInputStreamFromUrl(urlStr);
				File resultFile = fileUtils.writeDataToSDCrard(path, fileName,
				inputStream);
				if (resultFile == null) {
					Toast.makeText(context, "下载失败", Toast.LENGTH_LONG).show();
					return -1;
				}
			} catch (IOException e) {
				e.printStackTrace();
				return -1;
			} finally {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
					return -1;
				}
			}
		}
		Toast.makeText(context, "下载成功", Toast.LENGTH_LONG).show();
		return 0;
	}

	/**
	 * 得到输入流
	 * 
	 * @param urlstr
	 * @return
	 * @throws IOException
	 */
	public InputStream getInputStreamFromUrl(String urlstr) throws IOException {
		url = new URL(urlstr);
		HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
		InputStream is = urlconn.getInputStream();
		return is;
	}

}
